package icu.yougan.trade.controller;


import icu.yougan.trade.entity.Admin;
import icu.yougan.trade.entity.IdleItem;
import icu.yougan.trade.entity.User;
import icu.yougan.trade.enums.ErrorMsg;
import icu.yougan.trade.service.AdminService;
import icu.yougan.trade.service.IdleItemService;
import icu.yougan.trade.service.OrderService;
import icu.yougan.trade.service.UserService;
import icu.yougan.trade.utils.JwtTokenUtil;
import icu.yougan.trade.vo.R;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;

import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 管理员相关 控制层
 *@changeByLyh
 * @author: YouGan
 * @date: 2024-05-17
 */
@CrossOrigin
@RestController
@RequestMapping("admin")
@Validated
public class AdminController {

    @Resource
    private AdminService adminService;

    @Resource
    private IdleItemService idleItemService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;
    @Resource
    private AuthenticationManager authenticationManager;
    /**
     * 管理员登录
     *
     * @param accountNumber 账号
     * @param adminPassword 密码
     * @return 登录结果
     */
    @GetMapping("login")
    public R login(
            @RequestParam("accountNumber") @NotNull @NotEmpty String accountNumber,
            @RequestParam("adminPassword") @NotNull @NotEmpty String adminPassword
    ) {
        try {
            // 1. 认证逻辑（可复用用户认证体系）
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(accountNumber, adminPassword)
            );

            // 2. 生成管理员专属token（添加角色标识）
            UserDetails adminDetails = (UserDetails) authentication.getPrincipal();
            String token = jwtTokenUtil.generateToken(adminDetails, "ROLE_ADMIN");

            // 3. 获取完整管理员信息
           Admin admin = adminService.login(accountNumber,adminPassword);

            return R.success(Map.of(
                    "admin", admin,
                    "token", token,
                    "msg", "管理员登录成功"
            ));
        }catch (AuthenticationException e)
        {
            return R.fail(ErrorMsg.EMAIL_LOGIN_ERROR);
        }


    }



    /**
     * 查询管理员列表
     * @param page    分页大小
     * @param nums    分页页数
     * @return 管理员列表
     */
    @GetMapping("list")
    public R getAdminList(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "nums", required = false) Integer nums
    ) {
        int p = 1;
        int n = 8;
        if (null != page) {
            p = page > 0 ? page : 1;
        }
        if (null != nums) {
            n = nums > 0 ? nums : 8;
        }
        return R.success(adminService.getAdminList(p, n));
    }

    /**
     * 添加管理员
     *
     * @param admin   管理员信息
     * @return 结果
     */
    @PostMapping("add")
    public R addAdmin(
            @RequestBody Admin admin
    ) {
        if (adminService.addAdmin(admin)) {
            return R.success();
        }
        return R.fail(ErrorMsg.PARAM_ERROR);
    }

    /**
     * 商品列表
     * @param status  状态
     * @param page    分页大小
     * @param nums    分页页数
     * @return 管理员列表
     */
    @GetMapping("idleList")
    public R idleList(
            @RequestParam("status") @NotNull  Integer status,
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "nums", required = false) Integer nums
    ) {
        int p = 1;
        int n = 8;
        if (null != page) {
            p = page > 0 ? page : 1;
        }
        if (null != nums) {
            n = nums > 0 ? nums : 8;
        }
        return R.success(idleItemService.adminGetIdleList(status, p, n));
    }

    /**
     * 获取前端图表集
     * @param page    分页大小
     * @param nums    分页页数
     * @return 管理员列表
     */
    @GetMapping("getChartsData")
    public R getChartsData(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "nums", required = false) Integer nums
    ) {
        int p = 1;
        int n = 8;
        if (null != page) {
            p = page > 0 ? page : 1;
        }
        if (null != nums) {
            n = nums > 0 ? nums : 8;
        }
        return R.success(idleItemService.getChartsData(p, n));
    }
    /**
     * 更新违规状态
     *
     * @param id      用户id
     * @param status  状态
     * @return 结果
     */
    @GetMapping("updateIdleStatus")
    public R updateIdleStatus(
            @RequestParam("id") @NotNull Long id,
            @RequestParam("status") @NotNull Integer status
    ) {
        IdleItem idleItem = new IdleItem();
        idleItem.setId(id);
        idleItem.setIdleStatus(status.byteValue());
        if (idleItemService.updateIdleItem(idleItem)) {
            return R.success();
        }
        return R.fail(ErrorMsg.SYSTEM_ERROR);
    }

    /**
     * 查询订单列表
     * @param page    分页大小
     * @param nums    页数
     * @return 结果
     */
    @GetMapping("orderList")
    public R orderList(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "nums", required = false) Integer nums
    ) {
        int p = 1;
        int n = 8;
        if (null != page) {
            p = page > 0 ? page : 1;
        }
        if (null != nums) {
            n = nums > 0 ? nums : 8;
        }
        return R.success(orderService.getAllOrder(p, n));
    }

    /**
     * 删除订单
     *
     * @param id      订单id
     * @return 结果
     */
    @GetMapping("deleteOrder")
    public R deleteOrder(@RequestParam("id") @NotNull Long id
    ) {
        if (orderService.deleteOrder(id)) {
            return R.success();
        }
        return R.fail(ErrorMsg.SYSTEM_ERROR);
    }

    /**
     * 用户列表
     *
     * @param page    分页大小
     * @param nums    页数
     * @param status  状态
     * @return 列表
     */
    @GetMapping("userList")
    public R userList(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "nums", required = false) Integer nums,
            @RequestParam("status") @NotNull Integer status
    ) {
        int p = 1;
        int n = 8;
        if (null != page) {
            p = page > 0 ? page : 1;
        }
        if (null != nums) {
            n = nums > 0 ? nums : 8;
        }
        return R.success(userService.getUserByStatus(status, p, n));
    }
    @GetMapping("getCurrentAdmin")
    public R getCurrentAdmin(Authentication authentication)
    {
        return R.success(authentication.getName());
    }
    /**
     * 删除当前管理员
     * @param accountNumber
     * @return
     */
    @PostMapping("deleteAdmin")
    public R deleteAdmin(@RequestParam("accountNumber")String accountNumber)
    {
        return R.success(adminService.deleteAdmin(accountNumber));
    }
    /**
     * 更新用户状态
     *
     * @param id      id
     * @param status  状态
     * @return 结果
     */
    @GetMapping("updateUserStatus")
    public R updateUserStatus(
            @RequestParam("id") @NotNull Long id,
            @RequestParam("status") @NotNull  Integer status
    ) {
        User user = new User();
        user.setId(id);
        user.setUserStatus(status.byteValue());
        if (userService.updateUserInfo(user)) {
            return R.success();
        }

        return R.fail(ErrorMsg.SYSTEM_ERROR);
    }

    /**
     * 报表生成
     * @param startDate
     * @param endDate
     * @param type
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportReport")
    public void exportReport(
            @RequestParam String startDate,
            @RequestParam String endDate,
            @RequestParam String type,
            HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("系统报表_" + startDate + "_至_" + endDate, "UTF-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 根据类型导出不同数据
        switch (type) {
            case "orders":
                orderService.exportOrders(startDate, endDate, response.getOutputStream());
                break;
            case "users":
                userService.exportUsers(startDate, endDate, response.getOutputStream());
                break;
            case "goods":
                idleItemService.exportGoods(startDate, endDate, response.getOutputStream());
                break;
            default:
                // 导出全部数据
                orderService.exportOrders(startDate, endDate, response.getOutputStream());
                userService.exportUsers(startDate, endDate, response.getOutputStream());
                idleItemService.exportGoods(startDate, endDate, response.getOutputStream());
        }
    }
}